%%--------------------------------------------------------------------
%% Author: <vjache>
%% Created: 17.03.2009
%% Description: TODO: Add description to merge_sort
%%--------------------------------------------------------------------
-module(iter_generator).

%%--------------------------------------------------------------------
%% Include files
%%--------------------------------------------------------------------
-include("../include/iter.hrl").
%%--------------------------------------------------------------------
%% Exported Functions
%%--------------------------------------------------------------------
-export([
		 new/2,
		 open/1,
		 next/1,
		 close/1,
		 test/1
		 ]).

%%--------------------------------------------------------------------
%% API Functions
%%--------------------------------------------------------------------
new(Iter,GenFun) when is_function(GenFun,1)->
	iter:from_module(?MODULE, {Iter,GenFun}).
open({Iter,GenFun}) ->
	State=iter:open(Iter),
	{State,GenFun}.

next({State,GenFun}) ->
	{State1,Item}=iter:next(State),
	case Item of
			 ?EOF ->
				 {{State1,GenFun},?EOF};
			 _ ->
				 Iter=case GenFun(Item) of
					 List when is_list(List) ->
						 iter:from_list(List);
					 It when is_record(It, iter) ->
						 It
				 end,
				 GenState=iter:open(Iter),
				 next({State1,GenFun,GenState})
		 end;
next({State,GenFun,GenState}) ->
	{GenState1,Item}=iter:next(GenState),
	case Item of
		?EOF ->
			ok=iter:close(GenState1),
			next({State,GenFun});
		_ ->
			{{State,GenFun,GenState1},Item}
	end.

close({State,_GenFun,GenState}) ->
	ok=iter:close(State),
	ok=iter:close(GenState);
close({State,_GenFun}) ->
	ok=iter:close(State).

%%--------------------------------------------------------------------
%% Test Functions
%%--------------------------------------------------------------------

test(L) ->
	I=new(iter:from_list(L), 
		  fun(Item)->
				  iter:from_list(tuple_to_list(Item))
		  end),
	iter:foreach(I,fun(E)->
						   io:format("~p~n",[E])
				 end),
	ok.

%%--------------------------------------------------------------------
%% Local Functions
%%--------------------------------------------------------------------